/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: LoginApi.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.sdk.account;

import android.content.Context;

import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.constant.Fields;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.network.BParamsBuilder;
import io.bhex.baselib.network.HttpUtils;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.Utils.CookieUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.params.GetParams;
import io.bhex.baselib.network.params.IParams;
import io.bhex.baselib.network.params.PostParams;
import io.bhex.baselib.network.response.ResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.baselib.utils.MD5Utils;
import io.bhex.sdk.Urls;
import io.bhex.sdk.account.bean.BindBean;
import io.bhex.sdk.account.bean.LoginRequestBean;
import io.bhex.sdk.account.bean.LoginVerifyRequest;
import io.bhex.sdk.account.bean.OrderParamResponse;
import io.bhex.sdk.account.bean.QuickAuthCreateResponse;
import io.bhex.sdk.account.bean.RegisterRequestBean;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.data_manager.NetWorkApiManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.data_manager.TradeDataManager;

public class LoginApi {

    /**
     * 快速登录 - 创建认证身份
     * @param loginType
     * @param mobileCode
     * @param mobile
     * @param verifyCode
     * @param verifyCodeOrderId
     */
    public static void requestQuickAuthCreate(String loginType, String mobileCode, String mobile, String verifyCode, String verifyCodeOrderId,final SimpleResponseListener<QuickAuthCreateResponse> listener) {
        PostParams params = BParamsBuilder.post()
                .url(Urls.API_LOGIN_QUICK_AUTH_CREATE_URL)
                .addParam("login_type", loginType)
                .addParam("national_code", mobileCode)
                .addParam("mobile", mobile)
//                .addParam("email", email)
                .addParam("verify_code", verifyCode)
                .addParam("order_id", verifyCodeOrderId)
                .build();


        HttpUtils.getInstance().request(params, QuickAuthCreateResponse.class, new SimpleResponseListener<QuickAuthCreateResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
                if (listener != null)
                    listener.onBefore();
            }

            @Override
            public void onSuccess(QuickAuthCreateResponse data) {
                super.onSuccess(data);
                if (CodeUtils.isSuccess(data,true)) {
                    if (!data.isNeedCheckPassword()) {
                        UserInfoBean userInfoBean = data.getUser();
                        //保存一下用户的账号
//                        SPEx.set(AppData.SPKEY.USER_ACCOUNT_KEY + loginRequestBean.bEmail,loginRequestBean.account);
//                        SPEx.set(AppData.SPKEY.USER_ACCOUNT_MODE_KEY,loginRequestBean.bEmail);
                        //保存用户数据
                        AfterLoginNeedDo(userInfoBean);
                    }
                    if (listener != null)
                        listener.onSuccess(data);
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (listener != null)
                    listener.onFinish();
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (listener != null)
                    listener.onError(error);
            }
        });
    }

    /**
     * 快捷登录二次验证
     * @param requestId
     * @param password
     */
    public static void requestQuickAuthComfirm(String requestId, String password,final SimpleResponseListener<UserInfoBean> listener) {
        PostParams params = BParamsBuilder.post()
                .url(Urls.API_LOGIN_QUICK_AUTH_CONFIRM_URL)
                .addParam("request_id", requestId)
                .addParam("password", MD5Utils.encode(password))
                .build();


        HttpUtils.getInstance().request(params, UserInfoBean.class, new SimpleResponseListener<UserInfoBean>(){
            @Override
            public void onBefore() {
                super.onBefore();
                if (listener != null)
                    listener.onBefore();
            }

            @Override
            public void onSuccess(UserInfoBean data) {
                super.onSuccess(data);
                if (CodeUtils.isSuccess(data,true)) {
                    //保存一下用户的账号
//                    SPEx.set(AppData.SPKEY.USER_ACCOUNT_KEY + loginRequestBean.bEmail,loginRequestBean.account);
//                    SPEx.set(AppData.SPKEY.USER_ACCOUNT_MODE_KEY,loginRequestBean.bEmail);
                    //保存用户数据
                    AfterLoginNeedDo(data);
                    if (listener != null)
                        listener.onSuccess(data);
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (listener != null)
                    listener.onFinish();
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (listener != null)
                    listener.onError(error);
            }
        });
    }

    /**
     * 登录验证
     * @param requestData
     * @param listener
     */
    public static void RequestLoginVerify(final LoginVerifyRequest requestData, final SimpleResponseListener<BindBean> listener) {

        if (requestData == null)
            return;

//        PostParams params;
//        if (requestData.bEmail) {
//            params = BParamsBuilder.post()
//                    .url(Urls.API_LOGIN_EAMIL_VERIFY_URL)
//                    .addParam(Fields.FIELD_EAMIL, requestData.account)
//                    .addParam(Fields.FIELD_PASSWORD, MD5Utils.encode(requestData.pwd))
//                    .addParam("captcha_response", requestData.captcha_response)
//                    .addParam("captcha_id", requestData.captcha_id)
//                    .build();
//        }else{
//            params = BParamsBuilder.post()
//                    .url(Urls.API_LOGIN_MOBILE_VERIFY_URL)
//                    .addParam(Fields.FIELD_MOILE, requestData.account)
//                    .addParam(Fields.FIELD_PASSWORD, MD5Utils.encode(requestData.pwd))
//                    .addParam(Fields.FIELD_COUNTRY_CODE, requestData.mobileCode)
//                    .addParam("captcha_response", requestData.captcha_response)
//                    .addParam("captcha_id", requestData.captcha_id)
//                    .build();
//        }
        PostParams params = BParamsBuilder.post()
                .url(Urls.API_LOGIN_VERIFY_URL)
                .addParam("username", requestData.account)
                .addParam(Fields.FIELD_PASSWORD, MD5Utils.encode(requestData.pwd))
                .addParam("captcha_response", requestData.captcha_response)
                .addParam("captcha_id", requestData.captcha_id)
                .build();


        HttpUtils.getInstance().request(params, BindBean.class, listener);
    }


    /**
     * 登录
     * @param loginRequestBean
     */
    public static void RequestLogin(final LoginRequestBean loginRequestBean, final ResponseListener<UserInfoBean> listener) {

        if(loginRequestBean == null)
            return;

        PostParams params;
        params = BParamsBuilder.post()
                .url(Urls.API_LOGIN_URL)
                .addParam("request_id", loginRequestBean.requestId)
                .addParam("auth_type", loginRequestBean.authType)
                .addParam("order_id", loginRequestBean.orderId)//手机或者邮箱的二次验证请求返回的orderId  GA方式的验证不填
                .addParam("verify_code", loginRequestBean.verifyCode)
                .build();
        HttpUtils.getInstance().request(params, UserInfoBean.class, new SimpleResponseListener<UserInfoBean>() {
            @Override
            public void onBefore() {
                super.onBefore();
                if (listener != null)
                    listener.onBefore();
            }

            @Override
            public void onSuccess(UserInfoBean data) {
                super.onSuccess(data);
                if (CodeUtils.isSuccess(data,true)) {
                    //保存一下用户的账号
                    SPEx.set(AppData.SPKEY.USER_ACCOUNT_KEY + loginRequestBean.bEmail,loginRequestBean.account);
                    SPEx.set(AppData.SPKEY.USER_ACCOUNT_MODE_KEY,loginRequestBean.bEmail);
                    //保存用户数据
                    AfterLoginNeedDo(data);
                    if (listener != null)
                        listener.onSuccess(data);
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (listener != null)
                    listener.onFinish();
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (listener != null)
                    listener.onError(error);
            }
        });
    }


    /**
     * 获取用户信息
     * @param bEmail
     * @param account
     */
    public static void GetUserInfo(final boolean bEmail, final String account, final SimpleResponseListener<UserInfoBean> listener){
        PostParams params = BParamsBuilder.post()
                .url(Urls.API_USER_GET_BASE_INFO)
                .build();
        HttpUtils.getInstance().request(params, UserInfoBean.class,new SimpleResponseListener<UserInfoBean>(){

            @Override
            public void onSuccess(UserInfoBean data) {
                super.onSuccess(data);
                if (CodeUtils.isSuccess(data,true)) {
                    //保存一下用户的账号

                    AfterLoginNeedDo(data);

                    SPEx.set(AppData.SPKEY.USER_ACCOUNT_KEY + bEmail, account);
                    SPEx.set(AppData.SPKEY.USER_ACCOUNT_MODE_KEY, bEmail);
                    //保存用户数据
                    if (listener != null)
                        listener.onSuccess(data);
                }
            }
            @Override
            public void onFinish() {
                super.onFinish();
                if (listener != null)
                    listener.onFinish();
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (listener != null)
                    listener.onError(error);
            }

        });

    }

    /**
     * 获取用户信息
     */
    public static void GetUserInfo(){
        PostParams params = BParamsBuilder.post()
                .url(Urls.API_USER_GET_BASE_INFO)
                .build();
        HttpUtils.getInstance().request(params, UserInfoBean.class,new SimpleResponseListener<UserInfoBean>(){

            @Override
            public void onSuccess(UserInfoBean data) {
                super.onSuccess(data);
                if (CodeUtils.isSuccess(data,true)) {
                    //保存一下用户的账号

                    AfterLoginNeedDo(data);
                }
            }
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }

        });

    }

    /**
     * 获取用户信息
     */
    public static void GetUserInfo(SimpleResponseListener<UserInfoBean> listener){
        PostParams params = BParamsBuilder.post()
                .url(Urls.API_USER_GET_BASE_INFO)
                .build();
        HttpUtils.getInstance().request(params, UserInfoBean.class,listener);

    }

    /**
     * 退出登陆
     */
    public static void Logout(final SimpleResponseListener<ResultResponse> listener) {
        GetParams params = BParamsBuilder.get()
                .url(Urls.API_LOGOUT_URL)
                .build();
        HttpUtils.getInstance().request(params,ResultResponse.class,new SimpleResponseListener<ResultResponse>(){
            @Override
            public void onFinish() {
                super.onFinish();
                if (listener != null)
                    listener.onFinish();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    if (response.isSuccess()) {
                        UserInfo.clearUserInfo();
                    }
                    if (listener != null)
                        listener.onSuccess(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (listener != null)
                    listener.onError(error);
            }
        });
    }

    /**
     *
     * 注册
     *
     * */
    public static void RequestSignUp(String channel,final RegisterRequestBean requestBean, final ResponseListener<UserInfoBean> listener) {
        if (requestBean == null)
            return;

        PostParams params;
        if (requestBean.isEmail) {
            params = BParamsBuilder.post()
                    .url(Urls.API_REGISTER_EMAIL_URL)
                    .addParam(Fields.FIELD_EAMIL, requestBean.account)
                    .addParam(Fields.FIELD_PASSWORD1, MD5Utils.encode(requestBean.password1))
                    .addParam(Fields.FIELD_PASSWORD2, MD5Utils.encode(requestBean.password2))
                    .addParam(Fields.FIELD_ORDER_ID, requestBean.order_id)
                    .addParam(Fields.FIELD_VERIFY_CODE, requestBean.verify_code)
                    .addParam(Fields.FIELD_INVITE_CODE, requestBean.invite_code)
                    .addParam("source", channel)
                    .build();
        }else{
            params = BParamsBuilder.post()
                    .url(Urls.API_REGISTER_MOBILE_URL)
                    .addParam(Fields.FIELD_MOILE, requestBean.account)
                    .addParam(Fields.FIELD_COUNTRY_CODE, requestBean.mobileCode)
                    .addParam(Fields.FIELD_PASSWORD1, MD5Utils.encode(requestBean.password1))
                    .addParam(Fields.FIELD_PASSWORD2, MD5Utils.encode(requestBean.password2))
                    .addParam(Fields.FIELD_ORDER_ID, requestBean.order_id)
                    .addParam(Fields.FIELD_VERIFY_CODE, requestBean.verify_code)
                    .addParam(Fields.FIELD_INVITE_CODE, requestBean.invite_code)
                    .addParam("source", channel)
                    .build();
        }
        HttpUtils.getInstance().request(params, UserInfoBean.class, new SimpleResponseListener<UserInfoBean>() {

            @Override
            public void onSuccess(UserInfoBean data) {
                super.onSuccess(data);

                if (CodeUtils.isSuccess(data,true)) {
                    //保存一下用户的账号
                    SPEx.set(AppData.SPKEY.USER_ACCOUNT_KEY + requestBean.isEmail, requestBean.account);
                    SPEx.set(AppData.SPKEY.USER_ACCOUNT_MODE_KEY,requestBean.isEmail);
                    //保存用户数据
                    AfterLoginNeedDo(data);
                    if (listener != null)
                        listener.onSuccess(data);
                }
                /*else{
                    getUI().registerFailed(data.getMsg());
                }*/
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (listener != null)
                    listener.onFinish();
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (listener != null)
                    listener.onError(error);
            }

            @Override
            public void onBefore() {
                super.onBefore();
                if (listener != null)
                    listener.onBefore();
            }
        });
    }

    public static void AfterLoginNeedDo(UserInfoBean data){
        UserInfo.saveUserInfo(data);

        TradeDataManager.GetInstance().release();
        NetWorkApiManager.releaseTradeInstance();
        NetWorkApiManager.getTradeInstance();
        SymbolDataManager.GetInstance().getFavorites();
    }

    /**
     * 手势、指纹认证续期
     * @param authType 0 指纹  1 手势
     */
    public static void autoCheckToken(Context context, int authType, SimpleResponseListener<ResultResponse> listener) {
        PostParams params;
        params = BParamsBuilder.post()
                .url(authType==0?Urls.API_LOGIN_FINGER_URL:Urls.API_LOGIN_GESTURE_URL)
                .addParam("token",CookieUtils.getCookieToken())
//                .addParam("new_token", false)
                .build();
        HttpUtils.getInstance().request(params, ResultResponse.class, listener);
    }

    /**
     * 未登录状态验证
     * @param isVerifyEmail
     * @param requestId
     */
    public static void RequestVerifyBeforeLogin( boolean isVerifyEmail, String requestId, ResponseListener<OrderParamResponse> listener) {

        IParams params;
        if (isVerifyEmail) {
            params = BParamsBuilder.post()
                    .url(Urls.API_GET_VERIFY_CODE_EMAIL_AUTH_URL)
//                    .addParam("type","3")
                    .addParam("request_id",requestId)
                    .build();
        }else{
            params = BParamsBuilder.post()
                    .url(Urls.API_GET_VERIFY_CODE_MOBILE_AUTH_URL)
//                    .addParam("type","3")
                    .addParam("request_id",requestId)
                    .build();
        }
        HttpUtils.getInstance().request(params, OrderParamResponse.class, listener);
    }

    /**
     * 已登录状态验证
     * @param isVerifyEmail
     * @param type
     */
    public static void RequestVerifyAfterLogin(final boolean isVerifyEmail, String type, ResponseListener<OrderParamResponse> listener) {

        IParams params;
        if (isVerifyEmail) {
            params = BParamsBuilder.post()
                    .url(Urls.API_GET_VERIFY_CODE_EMAIL_URL)
                    .addParam("type",type)
//                    .addParam("captcha_response",token)
//                    .addParam("captcha_id", BuildConfig.DEEPKNOW_ID)
                    .build();
        }else{
            params = BParamsBuilder.post()
                    .url(Urls.API_GET_VERIFY_CODE_MOBILE_URL)
                    .addParam("type",type)
//                    .addParam("captcha_response",token)
//                    .addParam("captcha_id", BuildConfig.DEEPKNOW_ID)
                    .build();
        }
        HttpUtils.getInstance().request(params, OrderParamResponse.class, listener);
    }

}
